package com.apimarket.util.net;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * GET请求
 */
public class GetNetContext extends NetContext {
    private CloseableHttpClient client;

    private HttpGet httpGet;

    public GetNetContext(String url, Map<String, Object> params) {
        super(url, params);
        this.client = HttpClients.createDefault();
        this.httpGet = new HttpGet();
    }

    public static GetNetContext getNetContext(String url) {
        return new GetNetContext(url, null);
    }


    private CloseableHttpResponse getResponse() throws URISyntaxException, IOException {
        Map<String, Object> tmp = getParams();
        if (tmp != null && tmp.size() != 0) {
            StringBuilder builder = new StringBuilder(getUrl());
            builder.append("?");
            Set<String> keys = tmp.keySet();
            Iterator<String> iterator = keys.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                builder.append(key).append("=").append(tmp.get(key));
                if (iterator.hasNext()) builder.append("&");
            }
            setUrl(builder.toString());
        }

        httpGet.setURI(new URI(getUrl()));
        return client.execute(httpGet);
    }

    @Override
    public JsonNode getResultJson() throws IOException, URISyntaxException {
        try (CloseableHttpResponse response = getResponse()) {
            HttpEntity entity = response.getEntity();
            String jsonStr = getJsonStr(entity);
            EntityUtils.consume(entity);
            // 使用ObjectMapper readTree()方法将JSON解析为JsonNode
            return new ObjectMapper().readTree(jsonStr);
        }
    }
}
